<template>
  <div class="hotel-management">
    <div class="page-header">
      <h2>酒店管理</h2>
      <a-button type="primary" @click="showAddModal">
        <plus-outlined />
        添加酒店
      </a-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <a-row :gutter="16">
        <a-col :span="8">
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索酒店名称或地址"
            enter-button="搜索"
            @search="handleSearch"
          />
        </a-col>
        <a-col :span="6">
          <a-select v-model:value="starFilter" placeholder="星级筛选" style="width: 100%" @change="handleFilter">
            <a-select-option value="">全部星级</a-select-option>
            <a-select-option value="5">五星级</a-select-option>
            <a-select-option value="4">四星级</a-select-option>
            <a-select-option value="3">三星级</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-button @click="resetFilters">重置</a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 酒店列表表格 -->
    <a-table
      :columns="columns"
      :data-source="filteredHotels"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'imageUrl'">
          <img 
            :src="record.imageUrl || fallbackImg(record.id)" 
            :alt="record.name"
            style="width: 60px; height: 40px; object-fit: cover; border-radius: 4px;"
          />
        </template>
        <template v-if="column.key === 'star'">
          <a-tag color="gold">⭐ {{ record.star }}</a-tag>
        </template>
        <template v-if="column.key === 'priceAvg'">
          <span style="color: #e53935; font-weight: 600;">￥{{ record.priceAvg }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="editHotel(record)">编辑</a-button>
            <a-button type="link" size="small" danger @click="deleteHotel(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑酒店模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑酒店' : '添加酒店'"
      :width="600"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        :model="formData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        ref="formRef"
        :rules="formRules"
      >
        <a-form-item label="酒店名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入酒店名称" />
        </a-form-item>
        <a-form-item label="地址" name="address">
          <a-input v-model:value="formData.address" placeholder="请输入酒店地址" />
        </a-form-item>
        <a-form-item label="客服电话" name="tel">
          <a-input v-model:value="formData.tel" placeholder="请输入客服电话" />
        </a-form-item>
        <a-form-item label="星级" name="star">
          <a-select v-model:value="formData.star" placeholder="请选择星级">
            <a-select-option :value="1">一星级</a-select-option>
            <a-select-option :value="2">二星级</a-select-option>
            <a-select-option :value="3">三星级</a-select-option>
            <a-select-option :value="4">四星级</a-select-option>
            <a-select-option :value="5">五星级</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="均价" name="priceAvg">
          <a-input-number 
            v-model:value="formData.priceAvg" 
            placeholder="请输入均价"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="展示图片" name="imageUrl">
          <a-input v-model:value="formData.imageUrl" placeholder="请输入图片URL" />
        </a-form-item>
        <a-form-item label="酒店简介" name="description">
          <a-textarea 
            v-model:value="formData.description" 
            placeholder="请输入酒店简介"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { hotelAPI } from '@/api/hotel'

// 响应式数据
const hotels = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const starFilter = ref('')
const modalVisible = ref(false)
const isEdit = ref(false)
const formData = ref({
  id: null,
  name: '',
  address: '',
  tel: '',
  star: 3,
  priceAvg: 0,
  imageUrl: '',
  description: ''
})

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '酒店图片',
    dataIndex: 'imageUrl',
    key: 'imageUrl',
    width: 100
  },
  {
    title: '酒店名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
    ellipsis: true
  },
  {
    title: '客服电话',
    dataIndex: 'tel',
    key: 'tel',
    width: 120
  },
  {
    title: '星级',
    dataIndex: 'star',
    key: 'star',
    width: 80
  },
  {
    title: '均价',
    dataIndex: 'priceAvg',
    key: 'priceAvg',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right'
  }
]

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入酒店名称', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入酒店地址', trigger: 'blur' }
  ],
  star: [
    { required: true, message: '请选择星级', trigger: 'change' }
  ],
  priceAvg: [
    { required: true, message: '请输入均价', trigger: 'blur' }
  ]
}

// 计算属性 - 过滤后的酒店列表（仅用于星级筛选，搜索由后端处理）
const filteredHotels = computed(() => {
  let result = hotels.value

  // 按星级筛选（前端处理）
  if (starFilter.value) {
    result = result.filter(hotel => hotel.star == starFilter.value)
  }

  return result
})

// 加载酒店数据
const loadHotels = async () => {
  loading.value = true
  try {
    const res = await hotelAPI.list(pagination.value.current, pagination.value.pageSize, searchKeyword.value)
    const payload = res.data?.data || res.data || {}
    const list = Array.isArray(payload) ? payload : (payload.list || [])
    
    hotels.value = list.map(x => ({
      id: x.id,
      name: x.name,
      address: x.address,
      tel: x.tel,
      star: x.star,
      priceAvg: x.priceAvg || x.price_avg,
      imageUrl: x.imageUrl || x.image_url,
      description: x.description,
      createdAt: x.createdAt || x.created_at
    }))
    
    // 更新分页信息
    pagination.value.total = payload.total || list.length
  } catch (error) {
    console.error('加载酒店数据失败:', error)
    message.error('加载酒店数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  // 重置到第一页
  pagination.value.current = 1
  // 重新加载数据
  loadHotels()
}

// 筛选处理
const handleFilter = () => {
  // 重置到第一页
  pagination.value.current = 1
  // 重新加载数据
  loadHotels()
}

// 重置筛选
const resetFilters = () => {
  searchKeyword.value = ''
  starFilter.value = ''
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  loadHotels()
}

// 显示添加模态框
const showAddModal = () => {
  isEdit.value = false
  formData.value = {
    id: null,
    name: '',
    address: '',
    tel: '',
    star: 3,
    priceAvg: 0,
    imageUrl: '',
    description: ''
  }
  modalVisible.value = true
}

// 编辑酒店
const editHotel = (record) => {
  isEdit.value = true
  formData.value = { ...record }
  modalVisible.value = true
}

// 删除酒店
const deleteHotel = async (id) => {
  try {
    await hotelAPI.remove(id)
    message.success('删除成功')
    loadHotels()
  } catch (error) {
    console.error('删除酒店失败:', error)
    message.error('删除酒店失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (isEdit.value) {
      await hotelAPI.update(formData.value)
      message.success('更新成功')
    } else {
      await hotelAPI.create(formData.value)
      message.success('添加成功')
    }
    modalVisible.value = false
    loadHotels()
  } catch (error) {
    console.error('操作失败:', error)
    message.error(isEdit.value ? '更新失败' : '添加失败')
  }
}

// 取消操作
const handleCancel = () => {
  modalVisible.value = false
  formData.value = {
    id: null,
    name: '',
    address: '',
    tel: '',
    star: 3,
    priceAvg: 0,
    imageUrl: '',
    description: ''
  }
}

// 默认图片
const fallbackImg = (id) => `https://picsum.photos/seed/hotel-${id}/120/80`

// 组件挂载时加载数据
onMounted(() => {
  loadHotels()
})
</script>

<style scoped>
.hotel-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.search-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}
</style>
